<template>
  <section class="upload-img">
    <!-- {{fileList}}{{'fileList'}} -->
    <el-container v-if="updateConfig.isShowList">
      <el-main class="pad-no">
        <ul class="filelist-mulit flex-row flex-warp flex-align-c">
          <vuedraggable
            class="wrapper"
            v-model="fileList"
            @end="watchDragging"
          >
            <!-- :move="draggableMove" -->
            <transition-group>
              <li
                class="file-item"
                v-for="(item, index) in fileList"
                v-bind:key="index"
                @click="limiteChange"
                v-bind:style="{ cursor: hasLimit()?'pointer':'default'}"
              >
                <video
                  v-if="item.file_type == 'video'"
                  class="video-box pos-center"
                  :src="item.file_path"
                  controls="controls"
                />
                <!-- {{item.file_type =='url'}} -->
                <!-- <div style="display:flex;width: 120px;overflow: hidden;text-overflow: ellipsis;display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 3;">
                  链接：<el-input v-if="item.file_type =='url'" v-model="item.file_name" style="height:100px;"></el-input>
                  链接:<div v-if="item.file_type =='url'" >{{item.originname}}</div>
                   <div style="display:flex;width: 120px;overflow: hidden;text-overflow: ellipsis;display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 3;">
                                                    <div> 链接：{{item.originname}}</div>
                                                     
                                                  </div> -->
                <!-- </div> -->
                 <div v-if="item.file_type == 'url'" class="pos-col-center">
                      <div style="display:flex;width: 98px;overflow: hidden;text-overflow: ellipsis;display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 2;">
                        <div>{{item.originname}}</div>
                      </div>
                    </div>
                <audio
                  style="width: 100%;"
                  v-if="item.file_type == 'audio'"
                  class="audio-box"
                  preload="preload"
                  :src="item.file_path"
                  controls="controls"
                ></audio>
                <img
                  v-if="item.file_type == 'image'"
                  class="pos-center"
                  :src="item.file_path"
                />
                <label
                  class="status-label"
                  @mousemove="delFile('show',index,'fileList')"
                  @mouseout="delFile('none',index,'fileList')"
                >
                  <i
                    class="el-icon-check"
                  ></i>
                  <i
                    class="el-icon-close"
                    @click="delFileList(index,'fileList','mulit')"
                  ></i>
                </label>
              </li>
            </transition-group>
          </vuedraggable>
          <li
            v-show="!hasLimit()"
            class="file-item no-bor"
          >
            <div
              class="flex-row flex-align-c flex-justify-c update-load"
              @click="uploadTrigger"
            >
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </div>
          </li>
        </ul>
      </el-main>
    </el-container>
    <el-container v-if="updateConfig.modelFile">
      <el-upload
        v-show="!updateConfig.isCropper"
        ref="upload"
        class="avatar-uploader"
        :multiple="getType.hasMultiple"
        :action="autoloadUrl"
        :auto-upload="false"
        :accept="getType.fileType"
        :file-list="fileList"
        :show-file-list="false"
        :before-upload="beforeUploadVideo"
        :on-change="uploadOnChange"
      >
        <i class="el-icon-plus avatar-uploader-icon"></i>
        <!-- <el-progress v-else type="circle" :percentage="videoUploadPercent" style="margin-top:30px;"></el-progress> -->
      </el-upload>
      <!-- 默认为裁剪模式 -->
      <upload-cropper
        v-show="updateConfig.isCropper"
        :config="cropperConfig"
        :changeEvt="cutOnChange"
        :saveEvt="cutOnSave"
      ></upload-cropper>
    </el-container>
    <el-dialog
      :visible.sync="isShowModel"
      :append-to-body="true"
      @close="uploadTrigger('dialog')"
    >
      <!-- panleData{{panleData}} -->
      <div
        v-if="isShowModel"
        class="upload-modelbox"
        v-loading="mainLoing"
      >
        <el-container class="upload-main">
          <el-main>
            <el-tabs
              v-model="activeName"
              type="border-card"
              @tab-click="handleClick"
            >
              <el-tab-pane
                v-for="(item) in panleData"
                v-bind:key="item.name"
                :label="item.info"
                :name="item.name"
              >
                <span
                  slot="label"
                  class="flex-row flex-align-c flex-justify-c"
                ><i :class="item.icon"></i> <span>{{item.info}}</span></span>
                <!-- 上传图片 -->
                <ul
                  v-show="item.name == 'upimg'"
                  class="filelist-mulit flex-row flex-warp flex-align-c"
                >
                  <li
                    class="file-item"
                    v-for="(saveitem, saveindex) in saveList"
                    v-dragging="{ item: saveitem, list: saveList, group: 'saveList'}"
                    v-bind:key="saveitem.uid"
                  >
                    <img
                      class="pos-center"
                      :src="saveitem.url"
                    />
                     <!-- @mousemove="delFile('show',saveindex,'saveList')" -->
                      <!-- @mouseout="delFile('none',saveindex,'saveList')" -->
                    <!-- <video v-if="item.name == 'video'" class="video-box" :src="saveitem.url" controls="controls"/> -->
                    <label
                      class="status-label"
                    >
                      <i
                        v-if="!saveitem.showCheck"
                        class="el-icon-check"
                      ></i>
                      <i
                        v-else
                        class="el-icon-close"
                        @click="delFileList(saveindex,'saveList')"
                      ></i>
                    </label>
                  </li>
                  <li
                    v-if="!isLimitLen"
                    v-bind:class="['file-item','no-bor',updateConfig.isCropper?'cut-model':'']"
                  >
                    <el-upload
                      v-show="!updateConfig.isCropper"
                      ref="upload"
                      class="avatar-uploader"
                      :multiple="getType.hasMultiple"
                      :action="autoloadUrl"
                      :auto-upload="false"
                      :accept="getType.fileType"
                      :file-list="fileList"
                      :show-file-list="false"
                      :before-upload="beforeUploadVideo"
                      :on-change="uploadOnChange"
                    >
                      <i class="el-icon-plus avatar-uploader-icon"></i>
                      <!-- <el-progress v-else type="circle" :percentage="videoUploadPercent" style="margin-top:30px;"></el-progress> -->
                    </el-upload>
                    <!-- 默认为裁剪模式 -->
                    <upload-cropper
                      v-show="updateConfig.isCropper"
                      :config="cropperConfig"
                      :changeEvt="cutOnChange"
                      :saveEvt="cutOnSave"
                    ></upload-cropper>
                  </li>
                </ul>
                <span
                  v-show="item.name == 'upimg'"
                  class="font-help"
                >提示：第一张图片将被作为封面图，请保持每张图片的大小一致（可拖动调整显示顺序）</span>
                <!-- {{!isLimitLen}} -->

                <!-- 上传视频 -->
                <ul
                  v-show="item.name == 'video'"
                  class="filelist-mulit flex-row flex-warp flex-align-c"
                >
                  <li
                    class="file-item"
                    v-for="(saveitem, saveindex) in saveList"
                    v-dragging="{ item: saveitem, list: saveList, group: 'saveList'}"
                    v-bind:key="saveitem.uid"
                  >
                    <video
                      class="video-box pos-center"
                      :src="saveitem.url"
                      controls="controls"
                    />
                    <label
                      class="status-label"
                      @mousemove="delFile('show',saveindex,'saveList')"
                      @mouseout="delFile('none',saveindex,'saveList')"
                    >
                      <i
                        v-if="!saveitem.showCheck"
                        class="el-icon-check"
                      ></i>
                      <i
                        v-else
                        class="el-icon-close"
                        @click="delFileList(saveindex,'saveList')"
                      ></i>
                    </label>
                  </li>
                  <li class="file-item no-bor">
                    <el-upload
                      ref="upload"
                      class="avatar-uploader"
                      :multiple="getType.hasMultiple"
                      :action="autoloadUrl"
                      :auto-upload="false"
                      :accept="getType.fileType"
                      :file-list="fileList"
                      :show-file-list="false"
                      :before-upload="beforeUploadVideo"
                      :on-change="uploadOnChange"
                    >
                      <i class="el-icon-plus avatar-uploader-icon"></i>
                      <!-- <el-progress v-else type="circle" :percentage="videoUploadPercent" style="margin-top:30px;"></el-progress> -->
                    </el-upload>
                  </li>
                </ul>
                <span
                  v-show="item.name == 'video'"
                  class="font-help"
                >提示：视频上传单次不可传入多组视频</span>

                <!-- 上传音频 -->
                <ul
                  v-show="item.name == 'audio'"
                  class="filelist-mulit flex-row flex-warp flex-align-c"
                >
                  <li
                    class="file-item"
                    v-for="(saveitem, saveindex) in saveList"
                    v-dragging="{ item: saveitem, list: saveList, group: 'saveList'}"
                    v-bind:key="saveitem.uid"
                  >
                    <audio
                      class="audio-box"
                      preload="preload"
                      :src="saveitem.url"
                      controls="controls"
                    ></audio>
                    <label
                      class="status-label"
                      @mousemove="delFile('show',saveindex,'saveList')"
                      @mouseout="delFile('none',saveindex,'saveList')"
                    >
                      <i
                        v-if="!saveitem.showCheck"
                        class="el-icon-check"
                      ></i>
                      <i
                        v-else
                        class="el-icon-close"
                        @click="delFileList(saveindex,'saveList')"
                      ></i>
                    </label>
                  </li>
                  <li class="file-item no-bor">
                    <el-upload
                      ref="upload"
                      class="avatar-uploader"
                      :multiple="getType.hasMultiple"
                      :action="autoloadUrl"
                      :auto-upload="false"
                      :accept="getType.fileType"
                      :file-list="fileList"
                      :show-file-list="false"
                      :before-upload="beforeUploadVideo"
                      :on-change="uploadOnChange"
                    >
                      <i class="el-icon-plus avatar-uploader-icon"></i>
                      <!-- <el-progress v-else type="circle" :percentage="videoUploadPercent" style="margin-top:30px;"></el-progress> -->
                    </el-upload>
                  </li>
                </ul>
                <span
                  v-show="item.name == 'audio'"
                  class="font-help"
                >提示：音频上传单次不可传入多组音频</span>

                <!-- 浏览图片 -->
                <section v-if="activeName == 'getweb'">
                  <el-input
                    placeholder="请输入内容"
                    v-model="getwebPath"
                  >
                    <template slot="prepend">Http://</template>
                  </el-input>
                </section>
                <span
                  v-show="activeName == 'getweb'"
                  class="font-help"
                >提示：输入http路径，获取图片</span>

                <!-- 浏览图片 暂废弃-->
                <section v-show="item.name == 'viewimg'">
                  <!-- <div class="page-tab">
                    <el-tag
                      v-for="(tag,index) in viewimgTags.year"
                      v-bind:key="index"
                      :type="tag.val == getActiveY?'success':''"
                    >
                      <span @click="viewimgChange(tag.val,'activeY')">{{tag.name}}</span>
                    </el-tag>
                  </div> -->

                  <!-- <div class="page-tab">
                    <el-tag
                      v-for="(tag,index) in viewimgTags.month"
                      v-bind:key="index"
                      :type="tag.val == getActiveM?'success':''"
                    >
                      <span @click="viewimgChange(tag.val,'activeM')">{{tag.name}}</span>
                    </el-tag>
                  </div> -->

                  <ul class="filelist-mulit viewimgList flex-row flex-warp flex-align-c">
                    <li
                      class="file-item page-img"
                      v-for="(viewitem,viewindex) in viewimgList"
                      v-bind:key="viewitem.file_id"
                      v-cloak
                    >
                      <img
                        @click="viewimgSwitch(viewitem,viewindex)"
                        class="video-box pos-center"
                        :src="viewitem.file_path"
                      />
                      <label
                        :class="['status-label',getChooes?'chooes':'']"
                        @mousemove.stop="delFile('none',viewindex,'viewimgList',viewitem.file_id)"
                        @mouseout.stop="delFile('none',viewindex,'viewimgList',viewitem.file_id,'mouseout')"
                      >
                        <i
                          v-if="viewitem.showCheck"
                          class="el-icon-check"
                        ></i>
                        <i
                          v-else
                          class="el-icon-close"
                          @click="delFileList(viewindex,'viewimgList',viewitem.file_id,viewitem)"
                        ></i>
                      </label>
                    </li>
                  </ul>
                </section>

                <span
                  v-show="item.name == 'viewimg'"
                  class="font-help"
                >提示：点击图片选择后上传</span>
              </el-tab-pane>
            </el-tabs>
          </el-main>
          <el-footer v-bind:class="['footer flex-row flex-align-c flex-justify-b']">
            <div
              v-if="activeName == 'upimg'"
              class="flex-row flex-align-c flex-justify-b"
            >
              <span class="title-help">已上传{{getUploadLength}}张 模式:<span class="cut-model-type">{{updateConfig.isCropper ?'裁剪':'普通'}}</span></span>
              <el-select
                class="cut-model-option"
                v-model="cutOptionsModel"
                size="mini"
                placeholder="请选择"
                @change="cutOptionChange"
                style=""
              >
                <el-option
                  v-for="item in cutOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
            <div class="flex-row flex-align-c flex-justify-b footer-button">
              <!-- <el-button v-if="activeName == 'viewimg'" style="margin-left: 10px;" size="small" type="primary">确认</el-button> -->
              <!-- <el-button v-if="activeName == 'upimg'" style="margin-left: 10px;" plain size="small" type="primary" @click="cutmodelChange(config.isCropper)">{{config.isCropper?'普通上传':'图片裁剪'}}</el-button> -->
              <el-button
                v-if="activeName == 'getweb'"
                style="margin-left: 10px;"
                size="small"
                type="primary"
                @click="getwebImgPath"
              >确认</el-button>
              <!-- <el-button v-if="activeName == 'upimg'|| activeName == 'video'" style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传文件</el-button> -->
              <el-button
                v-if="activeName == 'upimg' || activeName == 'video' || activeName == 'audio'"
                style="margin-left: 10px;"
                size="small"
                type="primary"
                @click="submitUpload"
              >确认使用</el-button>
              <el-button
                v-if="activeName == 'viewimg'"
                style="margin-left: 10px;"
                size="small"
                type="primary"
                @click="viewimgAddChange"
              >确认使用</el-button>
              <el-button
                size="small"
                style="margin-left: 10px;"
                @click="uploadTrigger"
              >取消</el-button>
              <el-pagination
                @current-change="handleCurrentChange"
                :page-size="viewimgSize"
                :current-page.sync="viewimgPage"
                class="page-index"
                v-if="activeName == 'viewimg'"
                background
                layout="prev, pager, next"
                :total="viewimgAll"
              ></el-pagination>
            </div>
          </el-footer>
        </el-container>
      </div>
    </el-dialog>

  </section>
</template>

<script>
import vuedraggable from 'vuedraggable'
import Vue from 'vue'
import VueDND from 'awe-dnd'
import Cookies from 'js-cookie'
import $axios from 'axios'
import { uploadListImg, outUpload } from '@/api/upload'
import { regHttps } from '@/utils/regular'
import { Upload, Message } from 'element-ui'
import uploadCropper from '@/components/UploadCropper/index'
import defaultConfig from './utils/config'
Vue.use(VueDND)
export default {
  mixins: [defaultConfig.mixins],
  props: {
    defaultConfig: {
      type: Object,
      default: function() {
        return defaultConfig
      }
    },
    changeEvt: {
      type: Function,
      default: null,
      required: false
    },
    saveChangeEvt: {
      type: Function,
      default: null,
      required: false
    },
    modelChangeEvt: {
      type: Function,
      default: null,
      required: false
    }
  },
  data() {
    const $data = {
      isLimit: false,
      autoloadUrl: '',
      isShowModel: false,
      hasMultiple: false,
      cutmodelShow: false,
      cutOptionsModel: 'true',
      cropperConfig: {
        img: 'base64'
      },
      getwebPath: '',
      fileList: [],
      saveList: [],
      currentId: -1,
      cutOptions: [{
        value: 'false',
        label: '裁剪上传'
      }, {
        value: 'true',
        label: '普通上传'
      }],
      viewimgTags: defaultConfig.viewimgTags,
      submitList: [],
      viewimgList: [],
      viewimgSaveList: [],
      mainLoing: false,
      viewimgPage: 1,
      viewimgSize: 24,
      viewimgAll: 1,
      activeName: 'upimg',
      panleData: [],
      fileType: 'image/*,video/*'
    }
    return $data
  },
  created() {

  },
  components: {
    vuedraggable,
    Upload,
    uploadCropper
  },
  watch: {
    'config.initList': {
      handler(newData, oldData) {
        this.fileList = []
        if (Array.isArray(newData) && newData.length > 0) {
          this.$nextTick(() => {
            newData.forEach((item) => {
              const createImg = { 'file_type': '', 'showCheck': false, 'file_path': '' }
              Object.assign(createImg, item)
              let falg = true
              this.fileList.forEach(item1 => {
                createImg.file_id == item1.file_id && (falg = false)
              })
              falg && this.fileList.push(createImg)
            })
          })
        }
      },
      immediate: true,
      deep: true
    },
    'config.type': {
      handler(newData, oldData) {
        if (Array.isArray(newData) && newData.length > 0) {
          this.$nextTick(() => {
            const panle = []
            newData.map((item) => {
              if (item === 'image') {
                panle.push(...[{
                  name: 'upimg',
                  info: '上传图片',
                  icon: 'icon icon-album'
                }])
              } else if (item === 'getweb') {
                panle.push({
                  name: 'getweb',
                  info: '提取网络图片',
                  icon: 'icon icon-fujian'
                })
              } else if (item === 'video') {
                panle.push({
                  name: 'video',
                  info: '上传视频',
                  icon: 'icon icon-album'
                })
              } else if (item === 'audio') {
                panle.push({
                  name: 'audio',
                  info: '上传音频',
                  icon: 'icon icon-album'
                })
              }
            })
            const [{ name }] = panle
            this.activeName = name
            this.panleData = panle
          })
        }
      },
      immediate: true,
      deep: false
    },
    'config.saveList': {
      handler(newData, oldData) {
        if (Array.isArray(newData) && newData.length > 0) {
          this.saveList = []
          this.$nextTick(() => {
            newData.map(({ file_type = '', showCheck = false, file_path = '' }) => {
              this.saveList.push({
                file_type: file_type,
                showCheck: showCheck,
                file_path: file_path
              })
            })
          })
        }
      },
      immediate: true,
      deep: false
    }
  },
  computed: {
    getType: function() {
      const tabName = this.activeName
      const active = {
        fileType: tabName === 'upimg' ? 'image/*' : tabName === 'video' ? 'video/*' : 'audio/*',
        hasMultiple: tabName === 'upimg' && (this.updateConfig.isMultiple || this.updateConfig.isMore) && this.cutOptionsModel === 'true'
      }
      return active
    },
    isLimitLen() {
      return !this.updateConfig.isMore && this.updateConfig.limit === 1 && this.saveList.length >= 1
    },
    getActiveY() {
      return defaultConfig.viewimgTags.activeY
    },
    getActiveM() {
      return defaultConfig.viewimgTags.activeM
    },
    getUploadLength() {
      return this.submitList.length + this.fileList.length
    },
    getUploadSize() {
      return this.submitList.length + this.fileList.length
    },
    getChooes() {
      const id = this.currentId
      const saveList = this.viewimgSaveList
      if (id !== -1 && saveList.length > 0) {
        const getSave = saveList.filter(item => {
          item.id === id
        })
        if (getSave.length > 0) {
          return getSave[0].showCheck
        } else {
          return false
        }
      }
      return false
    }
  },
  mounted() {

  },
  methods: {
    watchDragging() {
      this.output()
    },
    // createPanle($data) {
    //   if (!!this.config.type && this.config.type.includes('image')) {
    //     $data.panleData.splice(0, 0, {
    //       name: 'upimg',
    //       info: '上传图片',
    //       icon: 'icon icon-album'
    //     })
    //   }

    //   if (!!this.config.type && this.config.type.includes('video')) {
    //     $data.panleData.splice(0, 0, {
    //       name: 'video',
    //       info: '上传视频',
    //       icon: 'icon icon-video'
    //     })
    //     !this.config.type.includes('image') && ($data.activeName = 'video')
    //     if (!this.config.type.includes('image')) {
    //       $data.panleData = [{
    //         name: 'video',
    //         info: '上传视频',
    //         icon: 'icon icon-video'
    //       }]
    //     }
    //   }

    //   if (!!this.config.type && this.config.type.includes('audio')) {
    //     $data.panleData.splice(0, 0, {
    //       name: 'audio',
    //       info: '上传音频',
    //       icon: 'icon icon-video'
    //     })
    //     !this.config.type.includes('image') && ($data.activeName = 'audio')
    //     if (!this.config.type.includes('image')) {
    //       $data.panleData = [{
    //         name: 'audio',
    //         info: '上传音频',
    //         icon: 'icon icon-videofill'
    //       }]
    //     }
    //   }
    // },
    uploadFileChange(val) {
      console.log(val)
    },
    clearFileList() {
      this.saveList = []
      this.submitList = []
      this.viewimgSaveList = []
    },
    limiteChange() {
      const hasLimit = this.hasLimit()
      if (hasLimit && this.fileList.length === 1) {
        if (!this.updateConfig.chooseFile) {
          this.isShowModel = true
        } else {
          if (
            Object.prototype.toString.call(this.modelChangeEvt) ===
            '[object Function]'
          ) {
            this.modelChangeEvt({ file_list: this.fileList }, this.updateConfig.bindKey)
          }
        }
      }
    },
    cutOptionChange(e) {
      // console.log(e)
      // this.$nextTick(item => {
      //   this.$set(this.updateConfig, 'isCropper', (e === 'true'))
      // })
    },
    handleCurrentChange(val) {
      this.viewimgChange(
        defaultConfig.viewimgTags.activeY,
        defaultConfig.viewimgTags.activeM,
        val
      )
    },
    getwebImgPath() {
      if (!regHttps(this.getwebPath)) {
        Message.error('https路径不合法')
      }

      // getWebImg(encodeURIComponent(this.getwebPath)).then(response => {
      //   console.log(response)
      //   if (!!response && response.errno === 0) {
      //     this.outsave([
      //       {
      //         url: response['message']
      //       }
      //     ])
      //     this.fileList.push({
      //       url: response['message']
      //     })
      //     this.output(this.fileList)
      //     Message({
      //       message: '上传成功！',
      //       type: 'success'
      //     })
      //   } else {
      //     Message({
      //       message: '上传失败！，请确认后重新输入！',
      //       type: 'error'
      //     })
      //   }
      // })
    },
    viewimgSwitch(viewimgItem) {
      const viewimgItemCopy = Object.assign({}, viewimgItem)
      let saveList = this.viewimgSaveList
      const hasLimit = !this.hasLimit()
      if ((!hasLimit || !this.updateConfig.isMore) && this.updateConfig.limit === 1) {
        saveList = []
        this.viewimgList.map((item, index) => {
          item.showCheck = false
        })
      } else {
        const hasChoose = this.viewimgList.filter(item => {
          return item.showCheck === true
        })

        if (hasChoose && (hasChoose.length >= this.updateConfig.limit)) {
          hasChoose[0]['showCheck'] = false
        }
      }

      if (saveList.length > 0) {
        const hasSave = saveList.findIndex(item => {
          return item.file_id === viewimgItemCopy.file_id
        })

        if (hasSave !== -1) {
          saveList.splice(hasSave, 1)
          viewimgItemCopy.showCheck = false
          this.currentId = -1
        } else {
          viewimgItem.showCheck = true
          this.viewimgSaveList.push(viewimgItemCopy)
          this.currentId = viewimgItem.file_id
        }
      } else {
        viewimgItem.showCheck = true
        this.viewimgSaveList.push(viewimgItem)
        this.currentId = viewimgItem.file_id
      }
    },
    viewimgAddChange() {
      const saveList = this.viewimgSaveList
      if (saveList.length > 0) {
        saveList.some(item => {
          const hasCover = this.fileList.findIndex((coverItem) => {
            return coverItem.file_id === item.file_id
          })
          if (hasCover === -1) {
            const hasLimit = !this.hasLimit()
            if (hasLimit) {
              this.fileList.push(item)
            } else {
              this.fileList = [item]
              return hasLimit
            }
          }
        })

        this.outsave(saveList)
        this.uploadTrigger()
        this.output(this.fileList)
        this.viewimgList.map(item => {
          item.showCheck = false
        })
      } else {
        Message({
          message: '请选择要添加的图片',
          type: 'error'
        })
      }
    },
    viewimgChange(val, timeType, page = 1) {
      this.mainLoing = true
      this.viewimgTags[timeType] = val
      uploadListImg({
        // year: defaultConfig.viewimgTags.activeY,
        page: page
      }).then(response => {
        const { data: { data: { file_list = {} } } } = response
        this.viewimgAll = Number(file_list.total) || 1
        this.viewimgList = file_list.data
        // console.log(file_list, 'this.viewimgList ')
        this.mainLoing = false
      })
    },
    toArr(obj) {
      const array = Object.keys(obj || {}).map(key => {
        obj[key]['_$name'] = key
        return obj[key]
      })
      return array
    },
    handleClick() {
      console.log(this.activeName)
      if (this.activeName === 'viewimg') {
        defaultConfig.viewimgTags.activeY = ''
        defaultConfig.viewimgTags.activeM = ''
        this.viewimgChange()
      }
      this.mainLoing = false
      this.clearFileList()
    },
    uploadTrigger(dialog) {
      if (!this.updateConfig.chooseFile) {
        this.isShowModel = (dialog === 'dialog') ? false : !this.isShowModel
      } else {
        if (
          Object.prototype.toString.call(this.modelChangeEvt) ===
          '[object Function]'
        ) {
          this.modelChangeEvt({ file_list: this.fileList }, this.updateConfig.bindKey)
        }
      }
      this.clearFileList()
    },
    useImg() {
      const scop = []
      const _this = this
      const hasLimit = this.hasLimit()
      if (_this.submitList.length > 0) {
        _this.submitList.map(item => {
          item.showCheck = false
          scop.push(item)
        })
        _this.outsave(scop)
        if (hasLimit && _this.fileList.length === 1) {
          _this.fileList = [...scop]
        } else {
          _this.fileList = [...this.fileList, ...scop]
        }
        // // console.log(scop)
        _this.output(scop)
        _this.uploadTrigger()
        _this.isLimit = hasLimit
      }
      // else {
      //     Message({
      //         message: "请先上传文件",
      //         type: "error"
      //     });
      // }
    },
    delFile(isShow, index, listType, listId, mouseType) {
      let hasCover = -1
      const newfile = Object.assign({}, this[listType][index])
      // console.log(this[listType], index)
      newfile['showCheck'] = isShow === 'show'
      this[listType].splice(index, 1, newfile)
      switch (listType) {
        case 'viewimgList':
          if (mouseType === 'mouseout') {
            hasCover = this.viewimgSaveList.findIndex((coverItem) => {
              return coverItem.file_id === listId
            })

            if (hasCover !== -1) {
              this.viewimgSaveList.splice(hasCover, 1)
            }
          }
          break
      }
    },
    delFileList(index, listType, listId, listItem) {
      switch (listType) {
        case 'saveList':
          this.saveList.splice(index, 1)
          this.isLimit = this.hasLimit()
          break
        case 'fileList':
          this.fileList.splice(index, 1)
          if (listId === 'mulit') {
            this.output('delFileList')
          }
          this.isLimit = this.hasLimit()
          break
        case 'viewimgList':
          console.log(index, listType)
          this.viewimgListDel(listId, index, listItem)
          break
      }
    },
    viewimgListDel(listId, index, listItem) {
      console.log('删除第index个', this.viewimgList, index)
      outUpload({
        file_id: listId
      }).then(response => {
        const { data: msgData } = response
        console.log(msgData)
        if (msgData.code === 1) {
          // 删除对应的存储的图片对象
          this.viewimgSwitch(listItem)
          Message({
            message: '删除成功！',
            type: 'success'
          })
          this.viewimgList.splice(index, 1)
        } else {
          Message({
            message: '删除失败！',
            type: 'error'
          })
        }
      })
    },
    submitUpload() {
      // console.log(this.saveList, 'uploadOnChange')
      if (this.saveList.length > 0) {
        const _this = this
        this.mainLoing = true
        const isImg = this.activeName === 'upimg'
        const uploadUrl = isImg ? _this.updateConfig.isMore ? defaultConfig.uploadImgsUrl : defaultConfig.uploadImgUrl : defaultConfig.uploadFileUrl
        const requerBase = uploadUrl.substr(1, uploadUrl.length - 1)
        const baseRequest = `${Cookies.get('BASE_API') || `${process.env.BASE_API}/`}${requerBase}`
        const formData = new FormData()
        const config = {
          'Content-Type': 'multipart/form-data'
        }
        const custormParams = _this.updateConfig.params
        this.saveList.map((item, index) => {
          // console.log('_this.config.isMore', _this.updateConfig.isMore)
          formData.append(
            `file[${index}]`,
            item.raw
          )
        })

        if (_this.updateConfig.isLocal) {
          formData.append(
            `default`,
            'local'
          )
        }

        if (custormParams) {
          const paramsKeys = Object.keys(custormParams)
          if (paramsKeys.length > 0) {
            paramsKeys.map(name => {
              formData.append(
                `${name}`,
                `${custormParams[`${name}`]}`
              )
            })
          }
        }

        // console.log('uploadING')
        $axios
          .post(baseRequest, formData, config)
          .then(function(response) {
            const {
              data: {
                code, msg, data
              }
            } = response
            // console.log(response.data, code, msg)
            if (code === 1) {
              if (data[0]['file_type'] === 'image') {
                data[0]['file_name'] = data[0]['originname']
              }
              Message({
                message: `${msg}`,
                type: 'success'
              })
              _this.submitSuccess(response)
              _this.useImg()
            } else {
              Message({
                message: `${msg}`,
                type: 'error'
              })
            }
            _this.mainLoing = false
          })
          .catch((err) => {
            console.log(err)
            Message.error('上传失败,请重新上传')
            _this.saveList = []
            _this.submitList = []
            _this.mainLoing = false
          })
      } else {
        Message({
          message: '请选择文件',
          type: 'error'
        })
      }
    },
    submitSuccess(fileList) {
      if (fileList.data) {
        const scopLits = fileList.data.data
        if (Array.isArray(scopLits)) {
          this.submitList = [...scopLits]
        } else {
          this.submitList.push(fileList.data.data)
        }
      }
      this.isLimit = this.hasLimit()
    },
    beforeUploadVideo(file) {
      const isLt10M = file.size / 1024 / 1024 < 10
      //   if (
      //     [
      //       "video/mp4",
      //       "video/ogg",
      //       "video/flv",
      //       "video/avi",
      //       "video/wmv",
      //       "video/rmvb"
      //     ].indexOf(file.type) == -1
      //   ) {
      //     Message.error("请上传正确的视频格式");
      //     return false;
      //   }
      console.log(file, 'beforeUploadVideo')
      if (!isLt10M) {
        Message.error('上传视频大小不能超过10MB!')
        return false
      }
    },
    uploadOnChange(file) {
      if (file.status === 'ready') {
        file.url = URL.createObjectURL(file.raw)
        file.showCheck = false
        this.saveList = [file]
        if (this.updateConfig.modelFile) {
          this.submitUpload()
        }
        // console.log("uploadfile", file);
      } else if (file.status === 'fail') {
        Message.error('文件上传出错，请刷新重试！')
      }
    },
    cutOnChange(isshow) {
      this.cutmodelShow = isshow
    },
    cutOnSave(file) {
      console.log(file)
      if (file.status === 'ready') {
        this.saveList.push(file)
        console.log(this.updateConfig.modelFile)
        if (this.updateConfig.modelFile) {
          this.submitUpload()
        }
      }
    },
    hasLimit() {
      const tabName = this.activeName
      if (this.updateConfig.limit) {
        const limit = (tabName === 'video') ? 1 : this.updateConfig.limit
        const has = limit < this.saveList.length || limit <= this.fileList.length
        return has
      }
      return false
    },
    output(event) {
      if (
        Object.prototype.toString.call(this.changeEvt) === '[object Function]'
      ) {
        console.log(this.fileList)
        this.changeEvt(this.fileList, this.updateConfig.bindKey, event)
      }
    },
    outsave(saveList) {
      if (
        Object.prototype.toString.call(this.saveChangeEvt) ===
        '[object Function]'
      ) {
        this.saveChangeEvt(saveList, this.updateConfig.bindKey)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
$upload-img: 100px;

.upload-modelbox {
  .el-pagination {
    margin: 0;
  }

  #pane-getweb {
    display: flex;
    position: relative;
    min-height: 174px;
    flex-direction: column;
    justify-content: center;

    & .font-help {
      position: absolute;
      bottom: 0;
      left: 0;
    }

    .el-input--mini .el-input__inner {
      height: 38px;
      line-height: 38px;
    }
  }

  .viewimgList.filelist-mulit {
    min-height: 266px;
  }

  & .footer {
    position: relative;
    padding: 0 15px;

    & .footer-button .el-button:nth-of-type(1) {
      margin-left: 0 !important;
    }

    .title-help {
      letter-spacing: 2px;

      .cut-model-type {
        font-weight: 600;
      }
    }

    /deep/ .cut-model-option {
      width: 120px;
      margin-left: 10px;

      .el-icon-circle-check {
        display: none !important;
      }
    }
  }

  & .footer.cut-model {
    z-index: -1;
  }

  .shadow {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    background: #000;
    opacity: 0.3;
    -webkit-transition: opacity 0.15s linear;
    -o-transition: opacity 0.15s linear;
    transition: opacity 0.15s linear;
  }

  .upload-main {
    background: #ffffff;
    margin: 0 auto;
    border: 2px dashed #e6e6e6;

    .page-tab {
      margin-bottom: 10px;

      .el-tag {
        margin-left: 10px;
        cursor: pointer;

        & span {
          width: 100%;
          height: 100%;
          display: inline-block;
          padding: 0 10px;
          margin: 0 -10px;
        }
      }

      & .el-tag:nth-of-type(1) {
        margin-left: 0 !important;
      }
    }

    .page-img {
      cursor: pointer;
    }

    .page-index {
      position: absolute;
      right: 0;
    }

    .font-help {
      display: inline-block;
      line-height: 1em;
      margin-top: 20px;
    }

    .el-main {
      padding: 0;
      box-shadow: none;

      .el-tabs {
        box-shadow: none;
        border: 0;

        & .el-tabs__header.is-top {
          z-index: 0;
        }

        & .el-tabs__header .icon {
          vertical-align: middle;
          margin-right: 3px;
        }
      }
    }
  }
}

.filelist-mulit {
  margin: 0;
  padding: 0;
  list-style: none;
  max-height: 400px;
  overflow-y: auto;
  overflow-x: hidden;

  & .file-item {
    display: inline-block;
    position: relative;
    overflow: hidden;
    z-index: 0;
    height: $upload-img;
    width: $upload-img;
    background-color: #fff;
    border: 1px solid #c0ccda;
    border-radius: 6px;
    box-sizing: border-box;
    margin-top: 10px;
    margin-right: 20px;
    padding: 0;
    
    img {
      width: 100%;
      height: auto;
    }
    // & .ath_in{
    //   display: flex;
    //   /deep/ .el-input__inner{
    //     height: 98px;
    //   }
    // }
    & .video-box {
      width: 123px;
      height: 123px;
    }

    & .audio-box {
      transform: scale(0.7);
      -ms-transform: scale(0.7);
      -moz-transform: scale(0.7);
      -webkit-transform: scale(0.7);
      -o-transform: scale(0.7);
      margin-left: -40px;
      margin-top: 36px;
    }

    & .update-load {
      cursor: pointer;
      width: $upload-img;
      height: $upload-img;
      background: #fafbff;
      border: 0;
      color: #a8abb0;
      border-radius: 5px;

      .icon {
        font-size: 48px;
        margin-right: 0;
      }
    }

    & .status-label {
      position: absolute;
      display: block;
      right: -17px;
      top: -7px;
      width: 46px;
      height: 26px;
      background: #ffffff;
      // background: #13ce66;
      text-align: center;
      transform: rotate(45deg);
      box-shadow: 0 1px 1px #ccc;
    }

    & .status-label {
      position: absolute;
      display: block;
      right: -17px;
      top: -7px;
      width: 46px;
      height: 26px;
      text-align: center;
      transform: rotate(45deg);
      box-shadow: 0 1px 1px #ccc;
      overflow: hidden;
    }

    & .status-label:hover {
      background: #ffffff;
      box-shadow: 0 !important;
    }

    &:hover {
      .el-icon-close{
        display: inline-block !important;
      }
      .el-icon-check{
        display: none !important;
      }
    }
  }

  .el-icon-check {
    width: 100%;
    height: 100%;
    color: #ffffff;
    background: #13ce66;
    font-size: 12px;
  }

  .el-icon-check:before {
    display: inline-block;
    margin-top: 12px;
    transform: rotate(-45deg);
  }

  .el-icon-close {
    display: none;
    margin-top: 12px;
    transform: rotate(-45deg);
    cursor: pointer;
    opacity: 1;
    color: #606266;
    background: #ffffff;
  }

  .no-bor {
    margin:0 !important;
    border-style: dashed !important;
  }

  .cut-model {
    border-radius: 0;
    overflow: visible;
  }

  // .avatar-uploader {
  //   border: 1px dashed #a8abb0;
  // }
  .avatar-uploader .el-upload {
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    vertical-align: bottom;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  /deep/ .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: $upload-img;
    height: $upload-img;
    line-height: $upload-img;
    text-align: center;
  }

  .avatar {
    width: $upload-img;
    height: $upload-img;
    display: block;
  }
}
</style>
